package com.example.myapplication.banner

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.FrameLayout
import androidx.viewpager.widget.ViewPager
import com.example.myapplication.R
import com.shuyu.gsyvideoplayer.GSYVideoManager
import java.util.*

/**
 * 自定义Banner轮播控件
 */
class BannerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private lateinit var viewPager: ViewPager
    private var adapter: BannerAdapter? = null
    private var timer: Timer? = null
    private var currentItem = 0
    private var delayTime = 3000L // 默认3秒切换
    private var isVideoPlaying = false
    private var isUserScrolling = false // 标记用户是否正在手动滑动
    private var isPaused = false // 标记是否处于暂停状态
    private var pausedVideoPosition = -1 // 暂停时正在播放的视频位置

    init {
        initView(context, attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?) {
        LayoutInflater.from(context).inflate(R.layout.banner_view, this, true)
        viewPager = findViewById(R.id.viewPager)
//        adapter = BannerAdapter(context) {
//            // 视频播放完成回调
//            onVideoPlayCompleted()
//        }
//        viewPager.adapter = adapter

        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                // 停止上一个视频播放
                adapter?.pauseVideoPlayback(currentItem)

                currentItem = position
                // 处理当前项（图片或视频）
                handleCurrentItem()
            }

            override fun onPageScrollStateChanged(state: Int) {
                // 当用户手动滑动结束时
            }
        })

        // 应用自定义属性
        attrs?.let { applyCustomAttributes(context, it) }
    }

    /**
     * 应用自定义属性
     */
    private fun applyCustomAttributes(context: Context, attrs: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BannerView)

        try {
            // 获取轮播间隔时间属性
            delayTime = typedArray.getInt(R.styleable.BannerView_delayTime, 3000).toLong()
        } finally {
            typedArray.recycle()
        }
    }

    /**
     * 设置Banner数据
     */
    fun setBannerData(data: List<BannerItem>) {
        if(adapter != null){
            // 停止当前的自动轮播和视频播放
            stopAutoPlay()
            adapter?.pauseVideoPlayback(currentItem)
        }

        adapter = BannerAdapter(context) {
            // 视频播放完成回调
            onVideoPlayCompleted()
        }
        viewPager.adapter = adapter

        // 重置状态
        currentItem = 0
        isVideoPlaying = false
        isPaused = false
        pausedVideoPosition = -1

        // 设置新数据
        adapter?.setData(data)
        adapter?.notifyDataSetChanged()

        // 重置ViewPager
        viewPager.currentItem = 0
        viewPager.offscreenPageLimit = 3

        // 处理当前项
        handleCurrentItem()
    }

    /**
     * 处理当前项（图片或视频）
     */
    private fun handleCurrentItem() {
        // 确保数据不为空
        if (adapter?.count == 0) return

        val currentItem = adapter?.getItem(viewPager.currentItem)
        if (currentItem?.type == BannerItemType.VIDEO) {
            isVideoPlaying = true
            // 停止自动轮播定时器
            stopAutoPlay()
            // 播放视频
            adapter?.playVideo(viewPager.currentItem)
        } else {
            isVideoPlaying = false
            // 如果不是用户手动滑动，则开始自动轮播定时器
            if (!isUserScrolling) {
                startAutoPlay()
            }
        }
    }

    /**
     * 开始自动轮播（仅用于图片）
     */
    fun startAutoPlay() {
        // 只有当前不是视频播放时才启动自动轮播
        if (adapter?.count == 0) return

        val currentItem = adapter?.getItem(viewPager.currentItem)
        if (currentItem?.type != BannerItemType.VIDEO) {
            stopAutoPlay()
            timer = Timer()
            timer?.schedule(object : TimerTask() {
                override fun run() {
                    post {
                        this@BannerView.currentItem = (this@BannerView.currentItem + 1) % adapter?.count!!
                        viewPager.currentItem = this@BannerView.currentItem
                    }
                }
            }, delayTime, delayTime)
        }
    }

    /**
     * 重新开始自动轮播（用于用户手动滑动后）
     */
    private fun restartAutoPlay() {
        stopAutoPlay()
        // 只有当前项是图片时才重新开始自动轮播
        if (adapter?.count == 0) return

        val currentItem = adapter?.getItem(viewPager.currentItem)
        if (currentItem?.type == BannerItemType.IMAGE) {
            timer = Timer()
            timer?.schedule(object : TimerTask() {
                override fun run() {
                    post {
                        this@BannerView.currentItem = (this@BannerView.currentItem + 1) % adapter?.count!!
                        viewPager.currentItem = this@BannerView.currentItem
                    }
                }
            }, delayTime, delayTime)
        } else if (currentItem?.type == BannerItemType.VIDEO) {
            // 如果是视频项，则播放视频
            adapter?.playVideo(viewPager.currentItem)
        }
    }

    /**
     * 停止自动轮播
     */
    fun stopAutoPlay() {
        timer?.cancel()
        timer = null
    }

    /**
     * 暂停播放（页面不可见时调用）
     */
    fun pause() {
        isPaused = true
        stopAutoPlay()

        // 如果当前正在播放视频，记录位置并暂停
        val currentItem = adapter?.getItem(viewPager.currentItem)
        if (currentItem?.type == BannerItemType.VIDEO) {
            pausedVideoPosition = viewPager.currentItem
            adapter?.pauseVideoPlayback(viewPager.currentItem)
        }
        
        // 暂停GSYVideoPlayer
        GSYVideoManager.onPause()
    }

    /**
     * 恢复播放（页面可见时调用）
     */
    fun resume() {
        isPaused = false

        // 恢复GSYVideoPlayer
        GSYVideoManager.onResume()

        // 如果之前有暂停的视频，恢复播放
        if (pausedVideoPosition >= 0) {
            adapter?.playVideo(pausedVideoPosition)
            pausedVideoPosition = -1
        } else {
            // 否则根据当前项类型处理
            handleCurrentItem()
        }
    }

    /**
     * 设置轮播间隔时间
     */
    fun setDelayTime(delayTime: Long) {
        this.delayTime = delayTime
    }

    /**
     * 视频播放完成回调
     */
    fun onVideoPlayCompleted() {
        isVideoPlaying = false
        // 视频播放完成后立即切换到下一个
        post {
            currentItem = (currentItem + 1) % adapter?.count!!
            viewPager.currentItem = currentItem
            handleCurrentItem()
        }
    }

    /**
     * 释放资源
     */
    fun release() {
        stopAutoPlay()
        adapter?.release()
        isUserScrolling = false
        isPaused = false
        pausedVideoPosition = -1
        
        // 释放GSYVideoPlayer资源
//        GSYVideoManager.releaseAllVideos()
    }
}